/********************************************
 * 功能说明: Web端Organization基础业务控制器
 * 模块名称:
 * 系统名称:
 * 软件版权: Frank
 * 系统版本: 1.0.0.1
 * 开发人员:
 * 开发时间: 2019-12-18 18:41:08
 * 审核人员:
 * 相关文档:
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.spring.arch.uaa.web.controller;

import com.codahale.metrics.annotation.Timed;
import com.spring.arch.common.dto.result.ResultDTO;
import com.spring.arch.uaa.errorcode.UaaErrorCode;
import com.spring.arch.uaa.web.dto.WebOrganizationDTO;
import com.spring.arch.uaa.web.dto.WebOrganizationTreeDTO;
import com.spring.arch.common.dto.result.ResultDTO;
import com.spring.arch.common.exception.ExceptionHolder;
import com.spring.arch.uaa.errorcode.UaaErrorCode;
import com.spring.arch.uaa.model.Organization;
import com.spring.arch.uaa.repository.OrganizationRepository;
import com.spring.arch.uaa.service.OrganizationService;
import com.spring.arch.uaa.web.converter.WebOrganizationConverter;
import com.spring.arch.uaa.web.dto.WebOrganizationDTO;
import com.spring.arch.uaa.web.dto.WebOrganizationTreeDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.validation.Valid;
import java.util.UUID;


/**
 * Web端Organization基础业务控制器
 *
 * @author
 * @version 1.0.0.1
 * @since 2019-12-18 18:41:08
 */
@Slf4j
@RestController
@RequestMapping(value = "/uaa/w/organization", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = {"Web端Organization管理API"})
public class WebOrganizationController {

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private OrganizationRepository organizationRepository;

    @Autowired
    private WebOrganizationConverter organizationConverter;

    @Autowired
    private EntityManager entityManager;

    /**
     * 新建操作
     *
     * @param organizationDTO 新建资源的DTO
     * @return 新建资源
     */
    @Timed
    @ApiOperation(value = "新建操作")
    @PutMapping
    public ResultDTO<WebOrganizationDTO> create(@RequestBody @Valid final WebOrganizationDTO organizationDTO) {
        final Organization model = this.organizationConverter.toModel(organizationDTO);
        this.organizationService.save(model);
        if(log.isInfoEnabled()) {
            log.info("{} instance {} was created.", Organization.class.getSimpleName(), model.getId());
        }
        return this.organizationConverter.toResultDTO(model);
    }

    /**
     * 删除操作
     *
     * @param id 实体对象ID
     * @return 操作结果
     */
    @Timed
    @ApiOperation(value = "删除操作")
    @DeleteMapping(value = "/{id}")
    public ResultDTO<Void> delete(@PathVariable final UUID id) {
        this.organizationService.delete(id);
        if(log.isInfoEnabled()) {
            log.info("{} instance {} was disable.", Organization.class.getSimpleName(), id);
        }
        return ResultDTO.success();
    }

    /**
     * 更新操作
     *
     * @param id   实体对象ID
     * @param name 修改后的部门名
     * @return 更新后资源
     */
    @Timed
    @ApiOperation(value = "更新操作")
    @PutMapping(value = "/{id}")
    public ResultDTO<WebOrganizationDTO> update(@PathVariable final UUID id, @RequestParam("name") String name) {
        final Organization model = this.organizationRepository.findById(id)
                .orElseThrow(() -> ExceptionHolder.serviceException(UaaErrorCode.E2001003001, id.toString()));

        entityManager.unwrap(Session.class).evict(model);
        model.setName(name);
        this.organizationService.save(model);
        if(log.isInfoEnabled()) {
            log.info("{} instance {} was updated.", Organization.class.getSimpleName(), model.getId());
        }
        return this.organizationConverter.toResultDTO(model);
    }

    /**
     * 获取集团的部门树
     */
    @Timed
    @ApiOperation(value = "获取集团的全部部门树")
    @PostMapping
    public ResultDTO<WebOrganizationTreeDTO> search(@RequestParam(value = "orgId") UUID orgId) {

        Organization organization = organizationRepository.findById(orgId).orElseThrow(() ->
                ExceptionHolder.serviceException(UaaErrorCode.E2001003001, orgId.toString()));

        return ResultDTO.success(this.organizationConverter.toTreeDTO(organization));
    }

    /**
     * 获取集团除项目外的部门树
     */
    @Timed
    @ApiOperation(value = "获取集团除项目外的部门树")
    @PostMapping("/group")
    public ResultDTO<WebOrganizationTreeDTO> searchByGroup(@RequestParam(value = "orgId") UUID orgId) {

        Organization organization = organizationRepository.findById(orgId).orElseThrow(() ->
                ExceptionHolder.serviceException(UaaErrorCode.E2001003001, orgId.toString()));

        return ResultDTO.success(this.organizationConverter.toTreeGroupDTO(organization));
    }
}
